from django.shortcuts import render, redirect
from app01 import models
from app01.utils.form import NumModelForm,PrettyEditModelForm
from app01.utils.pagination import Pagination


def pretty_list(request):
    """ 靓号列表 """

    # 功能：搜索号码
    # http://127.0.0.1:8000/pretty/list/?q=888
    # 前端传q=888给后台request.GET.get获取
    search_data = request.GET.get('q', "")  # (q,"")有值拿值，没值为空字符串
    data_dict = {}  # 筛选规则字典
    if search_data:
        data_dict["mobile__contains"] = search_data  # 查询mobile中包含 q即vlaue即888 的条目

    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
    page_object = Pagination(request, queryset,page_size=8)

    context = {
        "search_data": search_data,
        "queryset": page_object.page_queryset,  # 分完页数据
        "page_string": page_object.html(),  # 页码
    }
    # if request.method == "GET":  # 以“GET”可以 传参 ?=888, page=1
    return render(request, "pretty_list.html", context)


def pretty_add(request):
    """ 靓号新增 """
    if request.method == "GET":
        form = NumModelForm()
        return render(request, "pretty_add.html", {"form": form})
    form = NumModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request, "pretty_add.html", {"form": form})


def pretty_edit(request, nid):
    """ 靓号编辑 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_object)
        return render(request, "pretty_edit.html", {"form": form})
    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list")
    return render(request, "pretty_edit.html", {"form": form})


def pretty_delete(request, nid):
    """ 靓号删除 """
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")
